package day20170425.homework.dao.impl;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import day20170425.homework.dao.StudentDao;
import day20170425.homework.entity.StudentEntity;
import day20170425.homework.test.StudentTest;

/**
 * 业务类操作
 * 
 * @author 罗智壕-13424431416
 *
 *         2017年4月25日
 */
public class StudentDaoImpl implements StudentDao {
	
	/**
	 * xml路径
	 */
	private File file = new File("src/main/java/day20170425/homework/student.xml");
	/**
	 * SAXReader对象
	 */
	private SAXReader saxReader = new SAXReader();
	
	/**
	 * 读取文件 转换成Document  
	 */
	private Document document = null;
	
	/**
	 * 学生增加
	 * @param studentEntity	增加的对象
	 */
	public boolean addStudent(StudentEntity studentEntity){
		
		try {
			document = saxReader.read(file);
			//获取到根节点school
			Element root = document.getRootElement();
			//创建一个新的student节点
			Element newElement = root.addElement("student");
			String newId = String.valueOf(StudentTest.time);
			//设置属性id
			newElement.addAttribute("id", newId);
			//在刚刚创建的节点里面创建一个name节点
			Element name = newElement.addElement("name");
			//设置它的文本值
			name.setText(studentEntity.getName());
			//再创建一个age节点
			Element age = newElement.addElement("age");
			Integer newAge = studentEntity.getAge();
			//设置它的文本值
			age.setText(String.valueOf(newAge));
			//再创建一个sex节点
			Element sex = newElement.addElement("sex");
			//设置它的文本值
			sex.setText(studentEntity.getSex());
			//进行更新
			writeXMLDocument(document);
			return true;
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 学生删除
	 * @param studentEntity	删除的对象
	 */
	public boolean deleteStudent(StudentEntity studentEntity){
		try {
			document = saxReader.read(file);
			Element root = document.getRootElement();
			@SuppressWarnings("unchecked")
			//获取到根路径里面的节点
			Iterator<Element> it = root.elementIterator();
			while(it.hasNext()) {
				//每次循环拿到一个节点
	            Element element =  it.next();
	            //获取到当前这个节点的id
	            String id = element.attributeValue("id");
				String newId = String.valueOf(StudentTest.time);
				//如果id符合要求
	            if (newId.equals(id)) {
	                Element parent = element.getParent();
	                //进行删除
	                parent.remove(element);
	                //进行更新
	    			writeXMLDocument(document);
	    			return true;
	            }
	        }
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 学生修改
	 * @param studentEntity	修改的对象
	 */
	public boolean updateStudent(StudentEntity studentEntity){
		try {
			document = saxReader.read(file);
			//获取到根节点
			Element root = document.getRootElement();
			//拿到student这个节点
			@SuppressWarnings("unchecked")
			Iterator<Element> it = root.elementIterator();
			while(it.hasNext()) {
				//每次循环拿到一个节点
	            Element element = (Element) it.next();
	            //获取到当前这个节点的id
	            String id = element.attributeValue("id");
				String newId = String.valueOf(StudentTest.time);
				//如果id符合要求
	            if (id.equals(newId)) {
	            	//如果符合，拿到它子孙name节点
					Element nameEl = element.element("name");
					//修改它的文本值
					nameEl.setText(studentEntity.getName());
					//进行更新
					writeXMLDocument(document);
					return true;
	            }
	        }
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 学生查询
	 */
	@SuppressWarnings("unchecked")
	public List<StudentEntity> findAllStudent(){
		//创建一个新的容器返回出去（里面装有学生对象）
		List<StudentEntity> newList = new ArrayList<StudentEntity>();
		try {
			document = saxReader.read(file);
			//获取到根节点
			Element root = document.getRootElement();
			List<Node> sex = root.selectNodes("//sex");
			List<Node> age = root.selectNodes("//age");
			List<Node> name = root.selectNodes("//name");
			for(int i=0;i<name.size();i++){
				StudentEntity student = new StudentEntity();
				student.setName(name.get(i).getText());
				student.setAge(Integer.parseInt(age.get(i).getText()));
				student.setSex(sex.get(i).getText());
				newList.add(student);
			}
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		//返回新的容器
		return newList;
	}
	
	/**
     * 通过document对象将内存中的dom树保存到新的xml文档。
     * @param document
     * @throws Exception
     */
    public static void writeXMLDocument(Document document) throws Exception {
    	//设置XML文档输出格式
    	OutputFormat format = OutputFormat.createPrettyPrint(); 
    	//设置是否缩进
        format.setIndent(true); 
        //以空格方式实现缩进
        format.setIndent("   "); 
        //设置是否换行
        format.setNewlines(true); 
        //进行更新xml
        XMLWriter writer = new XMLWriter(new FileWriter("src/day20170425/homework/student.xml"),format);
        writer.write(document);
        writer.close();
    }
}
